package data.join.com.socket;

import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import data.join.com.utils.BaseThread;
import data.join.com.utils.MyLog;


public class NetWorkSDK extends BaseThread {
	private String TAG = NetWorkSDK.class.getSimpleName();

	private static NetWorkSDK netWorkSDK;

	private String Server_ip = "120.76.225.194";
	private int Server_port = 13033;

	private Socket mSocket;
	private InputStream mSocketReader;
	private OutputStream mSocketWriter;
	private volatile CountDownLatch mMsgCountDownLatch;
	private boolean forceReStartSocket = false;;

	public static NetWorkSDK getInstance(){
		if(netWorkSDK == null){
			netWorkSDK = new NetWorkSDK();
		}
		return netWorkSDK;
	}

	@Override
	public void run() {
		super.run();
		mainRun();
	}

	public void mainRun(){
		reStartSocket();
		
		while(true){

			if(forceReStartSocket){
				MyLog.D(TAG,"forceReStartSocket");
				reStartSocket();
			}

			MyLog.D(TAG,"等待发送数据");
			String msg = "carRecord";

			try {
				if(mSocketWriter != null) {
					mSocketWriter.write(msg.getBytes());   //开始执行发送定位数据包
				}else{
					await(TIME_WAIT);
					reStartSocket();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			await(TIME_WAIT);

		}
	}
	
	public boolean sendMsg(String msg){
		boolean ret = false;

		mMsgCountDownLatch = new CountDownLatch(1);
		
		try {
			if(mSocketWriter != null){
				MyLog.D(TAG,"sendMsg:"+msg);
				mSocketWriter.write(msg.getBytes());   //开始执行发送定位数据包
				mMsgCountDownLatch.await(20, TimeUnit.SECONDS);
			}else{
				MyLog.E(TAG,"发送数据失败,mSocketWriter为空");
			}
		} catch (IOException e) {
			e.printStackTrace();
			MyLog.E(TAG,"发送数据失败,IOException:" + e.getMessage());
		}catch (InterruptedException e) {
			e.printStackTrace();
			MyLog.E(TAG,"等待服务器应答中断,InterruptedException:" + e.getMessage());
		}
		
		ret = (mMsgCountDownLatch.getCount() == 0);
		mMsgCountDownLatch = null;
		MyLog.D(TAG,"发送数据结果 retTag=" + ret);
		
		return ret;
	}

	public void setForceReStartSocket(boolean b){
		forceReStartSocket = true;
		if(b){
			wakeUp();
		}
	}

	public void reStartSocket(){
		MyLog.W("Socket重连");
		closeNet();
		openNet();
		forceReStartSocket = false;
	}
	
	public void closeNet(){
		try {
				if (mSocketReader != null) {
					mSocketReader.close();
					mSocketReader = null;
				}
				if (mSocketWriter != null) {
					mSocketWriter.close();
					mSocketWriter = null;
				}
				if (mSocket != null) {
					mSocket.close();
					mSocket = null;
				}
		} catch (IOException e) {
				e.printStackTrace();
		}
		MyLog.W("Socket关闭");
	}
	
	/**
	 * 重新连接socket
	 *  Author: xiao feng Create at 2015-11-2 下午4:29:48
	 * TODO
	 *
	 */
	public void openNet(){
		try {

			MyLog.D(TAG,"openNet:Server_ip="+Server_ip+",Server_port="+Server_port);
			
			mSocket = new Socket(Server_ip, Server_port);
			mSocket.setKeepAlive(true);
			mSocket.setTcpNoDelay(true);
			
			mSocketReader = mSocket.getInputStream();
			mSocketWriter = mSocket.getOutputStream();

			startRead();

			MyLog.D(TAG,"socket连接成功");
		} catch (Exception e) {
			MyLog.D("Exception  创建Socket连接失败  " +  e.getMessage());
			closeNet();
		}
	}

	private void startRead(){
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				byte[] buffer = new byte[512];  
				int temp = 0;
	            try {
					while ((mSocketReader!=null) && ((temp = mSocketReader.read(buffer)) != -1)) {
						receiverMessage(new String(buffer, 0, temp));
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					MyLog.D(TAG,"Read Thread IOException:"+e.toString());
				}
			}
		}.start();
	}
	
	private void receiverMessage(String msg){

		MyLog.D(TAG,"接收到服务器下发的数据协议包:"+msg);

		if(msg.contains("*MG20YBA#")||msg.contains("*MG20YAJ#")){
			if(mMsgCountDownLatch != null) {
				mMsgCountDownLatch.countDown();
			}else{
				MyLog.E(TAG,"ERROR:mMsgCountDownLatch is NULL");
			}
		}
	}
	
	public void sleep(int dur){
		try {
			Thread.sleep(dur);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
